<?php

/**
 * MVM_MALL 网上商店系统  系统函数库
 * ============================================================================
 * 版权所有 (C) 2007-2010 www.mvmmall.com，并保留所有权利。
 * 网站地址: http://www.mvmmall.com
 * ----------------------------------------------------------------------------
 * 这是一个免费开源的软件；这意味着您可以在不用于商业目的的前提下对程序代码
 * 进行修改、使用和再发布。
 * ============================================================================
 * $Author:  www.mvmmall.com  $
 * $Date: 2008-04-12 $
 * $Id: global.func.php  www.mvmmall.com$
 * ---------------------------------------------
*/

if(!defined('MVMMALL')) {
	exit('Access Denied');
}
$mvm_version= '5.5.0';
$lang_powered_mvmmall  = '<A href="http://www.mvmmall.com" target="_blank" style="font-size:10px">Powered by <strong><span style="color: #3366FF">MvMmall</span> <span style="color: #FF9966">v'.$mvm_version.'</span></strong></A> ';
$mvmmall_version       = "<script src='http://mvmmall.com/mvmmallversion.php?mvm_version=$mvm_version'></script>";
function daddslashes($string, $force = 0) {
	!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
	if(!MAGIC_QUOTES_GPC || $force) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = daddslashes($val, $force);
			}
		} else {
			$string = addslashes($string);
		}
	}
	return $string;
}
function dreferer($default = '') {
	global $referer;
	$default = empty($default) ? GetBaseUrl('index') : '';
	if(empty($referer) && isset($GLOBALS['_SERVER']['HTTP_REFERER'])) {
		$referer = preg_replace("/([\?&])((sid\=[a-z0-9]{6})(&|$))/i", '\\1', $GLOBALS['_SERVER']['HTTP_REFERER']);
		$referer = substr($referer, -1) == '?' ? substr($referer, 0, -1) : $referer;
	} else {
		$referer = dhtmlchars($referer);
	}
	if(!preg_match("/(\.php|[a-z]+(\-\d+)+\.html)/", $referer) || strpos($referer, 'logging.php')) {
		$referer = $default;
	}
	
	return $referer;
}
function filtering($str){
	 return trim(strtr(dhtmlchars($str), array("\\\\" => "\\\\\\\\", '\?'=>'','_' => '\_', '%' => '\%')));
}

function drop_check($var,$out){
	global ${$out.'_y'},${$out.'_n'};
	if($var) ${$out.'_y'}='checked'; else ${$out.'_n'}='checked';
}
//格式化js输入时间
function time_format($date){
    $arr   = explode('-',$date);
    return  mktime(0,0,0,$arr[1],$arr[2],$arr[0]);
}

//建立缓存文件
function make_cache($array,$name){
		$configinfo = "<?PHP\n \$$name= ". var_export($array , true) .";\n";
		touch(MVMMALL_CACHE."$name.cache.php");
		$fp = fopen(MVMMALL_CACHE."$name.cache.php", 'w');
		flock($fp,LOCK_EX);
		fwrite($fp, $configinfo);
		fclose($fp);
		@chmod(MVMMALL_CACHE."$name.cache.php",0777);
		return true;
}

 function writeover($filename,$data,$method="rb+",$iflock=1,$check=1,$chmod=1){
        $check && strpos($filename,'..')!==false && exit('Forbidden');
        touch($filename);
        $handle=fopen($filename,$method);
        if($iflock){
            flock($handle,LOCK_EX);
        }
        fwrite($handle,$data);
        if($method=="rb+") ftruncate($handle,strlen($data));
        fclose($handle);
        $chmod && @chmod($filename,0777);
    }
    
//提示信息
function show_msg($title,$url="") {
	@extract($GLOBALS, EXTR_SKIP);
    global $lang;
    if ($url == "") {
        $jump='';
    }elseif ($url == "close") {
        $url = "window.close()";
        if ($str != "") { echo "<script language='javascript'>alert('$str');$url;</script>"; }
        else { echo "<script language='javascript'>$url;</script>"; }
    }else {
        $jump="<meta http-equiv=\"refresh\" content=\"4;url=$url\"/>";
    }
    $str = $lang[$title];
    require_once template('showmsg');
    $output = str_replace(array('<!--<!---->','<!---->',"\r",substr(MVMMALL_ROOT,0,-1)),'',ob_get_contents());
    ob_end_clean();
    echo $output; unset($output);exit;
    exit;
    }

/**
 * 重定向浏览器到指定的 URL
 *
 * @param string $url 要重定向的 url
 * @param int $delay 等待多少秒以后跳转
 * @param bool $js 指示是否返回用于跳转的 JavaScript 代码
 * @param bool $jsWrapped 指示返回 JavaScript 代码时是否使用 <script> 标签进行包装
 * @param bool $return 指示是否返回生成的 JavaScript 代码
 */
function move_page($url, $delay = 0, $js = false, $jsWrapped = true, $return = false)
{
    $delay = (int)$delay;
    if (!$js) {
        if (headers_sent() || $delay > 0) {
            echo <<<EOT
    <html>
    <head>
    <meta http-equiv="refresh" content="{$delay};URL={$url}" />
    </head>
    </html>
EOT;
            exit;
        } else {
            header("Location: {$url}");
            exit;
        }
    }

    $out = '';
    if ($jsWrapped) {
        $out .= '<script language="JavaScript" type="text/javascript">';
    }
    $url = rawurlencode($url);
    if ($delay > 0) {
        $out .= "window.setTimeOut(function () { document.location='{$url}'; }, {$delay});";
    } else {
        $out .= "document.location='{$url}';";
    }
    if ($jsWrapped) {
        $out .= '</script>';
    }

    if ($return) {
        return $out;
    }

    echo $out;
    exit;
}

// 空字母的时候把1return
function isblank($str) {
	if(eregi("[^[:space:]]",$str)) { return 0; } else { return 1; }
	return 0;
}

// 数字，英文字母的时候把1return
function isalnum($str) {
	if(eregi("[^0-9a-zA-Z\_]",$str)) { return 0; } else { return 1; }
}

// 把URL, Mail自动识别，做成link
function autolink($str) {

	$homepage_pattern = "(http://|ftp://|telnet:)[[:alnum:]-]+(\.[[:alnum:]-]+)+(:[[:digit:]]+)?(/[^\/:*\"<>|&?]+)*(\?[^\/:*\"<>|&?]+(&amp;[^\/:*\"<>|&?]+)*)?";

	$str = ereg_replace("$homepage_pattern", "<A href=\"\\0\" target=\"_blank\">\\0</A>", $str);

	$email_pattern = "[[:alnum:]._-]+@[[:alnum:]-]+(\.[[:alnum:]-]+)+";
	$str = ereg_replace("$email_pattern", "<A href=\"mailto:\\0\">\\0</A>", $str);

	return $str;
}
// 删除HTML 中攻击标记
function dhtmlchars($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = dhtmlchars($val);
		}
	} else {
		$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
		str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
	}
	return $string;
}


//隐藏,我喜欢manggo
function mango_encode($str) {
	$str = base64_encode($str);
	$str = urlencode($str);
	return $str;
}

// 解除隐藏.
function mango_decode($str) {
	$str = urldecode($str);
	$str = base64_decode($str);
	return $str;
}

// 骂人，广告等过滤
function bad_check($badword,$str,$divide = ",") {
	$badword = preg_replace('/'.$divide.'/','|',$badword);
	if(preg_match('/'.$badword.'/',$str,$match)) { return $match[0]; }
	return 0;
}

// 剪断文字长度
function cut_str($string,$length) {
      preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $string, $info);  
        for($i=0; $i<count($info[0]); $i++) {
                $str .= $info[0][$i];
                $j = ord($info[0][$i]) > 127 ? $j + 2 : $j + 1;
                if ($j > $length - 3) {
                        return $str.'...';
                }
        }
        return join('', $info[0]);
}

// 删除文件的函数
function file_unlink($file_name) {
	if(file_exists($file_name)) {
		@chmod($file_name,0777);
		$area_lord = @unlink($file_name);
	}
	return $area_lord;
}

// 求指定目录(文件夹)中的信息
function get_dirinfo($dir_path,$file='') {
	$area_lord = @opendir($dir_path);
	while($dir_info = @readdir($area_lord)) {
	    if($dir_info != '.' && $dir_info != '..' && $dir_info != '.svn' && $dir_info != 'index.htm') {
	        if ($file!=''){
	            if(eregi($file,$dir_info)) {
	                $dir_file_name[] = $dir_info;
	            }
	        }else {
	            $dir_file_name[] = $dir_info;
	        }

	    }
	}
	closedir($area_lord);
	return $dir_file_name;
}

// 读取文件
function get_read_file($fc_filename) {
	if(!file_exists($fc_filename)) return '';

	$fp = fopen($fc_filename,"r");
	$fp_str = fread($fp, filesize($fc_filename));
	fclose($fp);

	return $fp_str;
}

//邮件发送
function smtp_mail($email,$mail_subject,$mail_content,$type='html') {   
    require_once 'include/class.phpmailer.php';
    $mail = new PHPMailer();
    $mail->CharSet = "utf-8"; // 设置编码
    if ($GLOBALS['mm_mail_method']==1){
        $mail->IsMail();// 使用 mail
    }elseif ($GLOBALS['mm_mail_method']==2){
        $mail->IsSendmail();// 使用 sendmail
    }else {
       $mail->IsSMTP();// 使用 SMTP 
    }
    $mail->Host     = $GLOBALS['mm_mail_smtphost'];  // 比如：smtp.163.com;mail.tsingfeng.com
    $GLOBALS['mm_mail_smtpauth'] && $mail->SMTPAuth = true;  // 认证功能  
    $mail->Username = $GLOBALS['mm_mail_smtpuser'];  // 用户名
    $mail->Password = $GLOBALS['mm_mail_smtppass']; // 密码
    $mail->From     = $GLOBALS['mm_mail_smtpfrom']; //设置发件人的邮箱地址
    $mail->FromName = $GLOBALS['mm_mail_name']; //设置发件人的姓名
    $mail->AddAddress($email,''); //设置收件的地址
    $mail->AddReplyTo($GLOBALS['mm_mail_smtpfrom'],$GLOBALS['mm_mail_name']);//回复人
    $mail->WordWrap = 50;                                 //50字换行
    //$mail->AddAttachment("/tmp/image.jpg", "new.jpg");    // 附件
    $mail->Subject = $mail_subject;
    if ($type=='html'){
      $mail->IsHTML(true); // set email format to HTML 
      $mail->Body    = $mail_content; 
    }else {
       $mail->AltBody = dhtmlchars($mail_content);//不支持html时，显示的文本 
    }
    if($mail->Send()) return true;
}



// 下级分类导航
function tree_category($cat_id,$fid) {
    global $tablepre,$db,$mm_tree_stat;
   	 $cat_rt = $db->get_one("SELECT uid,category_id,use_direct FROM `{$tablepre}category` WHERE category_id = '$cat_id' AND use_direct = 1 ");
     $cat_rt == false && $cat_id = $fid;
    $sql = " SELECT uid,category_id,category_name,use_direct,category_rank FROM `{$tablepre}category` WHERE category_id='$cat_id' AND use_direct = 1 ORDER BY category_rank ASC";
    $result = $db->query($sql);
    while($rt = $db->fetch_array($result)) {
        $rt['title']  = $rt['category_name'];
        $rt['url']    = GetBaseUrl('category',$rt['uid']);
        $row[]        = $rt;
        unset($rt);
    }
    return $row;
}

  
function goods_stock_check($ps_goid,$goods_num) {
    global $mm_stock_use;
    if ($mm_stock_use==1) {
        $list = $GLOBALS[db]->get_one("SELECT uid,goods_stock FROM `{$GLOBALS[tablepre]}goods_table` WHERE uid = '$ps_goid'");
        return  $list[goods_stock] >= $goods_num?1:0;
    }else {
        return 1;
    }
}

function ShowPage($ps_pname='page_company'){
    $pa_list  = $GLOBALS['db']->get_one("SELECT uid,page_grant,use_html,page_subject,page_body,page_key,page_desc,approval_date FROM `{$GLOBALS['tablepre']}page_table` WHERE page_name = '$ps_pname' AND approval_date > 0 ");
    //if ($pa_list==false) show_msg($GLOBALS[lang][db_avess],dreferer());
    if($GLOBALS['m_check_rank'] < $pa_list['page_grant']) {
        if(!$GLOBALS['m_check_id']) {
            show_msg('grant_page',GetBaseUrl('logging','login'));
        } else {
        	show_msg('grant_page_member',dreferer()); 
        }
    }
    $page['conter'] = $pa_list['use_html']? $pa_list['page_body']:dhtmlchars($pa_list['page_body']);
    if($pa_list['uid']) {
        $page['title'] = $pa_list['page_subject'];
        $page['page_key'] = $pa_list['page_key'];
        $page['page_desc'] = $pa_list['page_desc'];
    } else {
        return 0;
    }
    $page['page_key']  = $pa_list['page_key'];
    $page['page_desc'] = $pa_list['page_desc'];
    unset($pa_list);
    return $page;
}

//提取分类导航
function urlcat($arr){
	global $str;
	if ($arr[0]!=false) {
		$url = $GLOBALS['rewrite'] == '1' ? "category-$arr[0]-1.html":"category.php?action=$arr[0]";
		$str = "<a href=$url>$arr[1]</a>&raquo;".$str;
		urlcat($GLOBALS['tree']->get_parent($arr[0]));
	}
	return  '<a href='.GetBaseUrl('index').'>'.$GLOBALS['lang']['pag_home'].'</a> &raquo; '.$str;
}
function make_navigation($navi_text,$now_url){
	$str  = '<a href='.GetBaseUrl('index').'>'.$GLOBALS['lang']['pag_home'].'</a> &raquo; ';
	$str .= "<span><a href=$now_url>$navi_text</a></span>";

	return $str;
}
// banner处理,$status 广告位置 $num 第几个 $limit_width 宽 $limit_height 高
function banner($status="index_left",$num="1",$limit_width="0",$limit_height="0") {
    global $db,$tablepre,$m_now_time;
    $banner_array = array();
    if(file_exists(MVMMALL_CACHE.'banner_array.cache.php')){
        include MVMMALL_CACHE.'banner_array.cache.php';
    }else {
        $result = $db->query("SELECT * FROM `{$tablepre}banner_table` WHERE  start_date < '$m_now_time' AND end_date > '$m_now_time'  ORDER BY `uid` DESC");
        while($rt =  $db->fetch_array($result)) {
            $banner_array[]=$rt;
        }
        make_cache($banner_array,'banner_array');
    }
    unset($rt);
    foreach ($banner_array as $key=>$rt) 
    {
        $limit_width  && $rt['banner_width']  = $limit_width;
        $limit_height && $rt['banner_height'] = $limit_height;
        !$rt['banner_target'] && $rt['banner_target'] = '_blank';
        if ($rt['banner_point']==$status){
            $i=1;
            if($num==$i){
                if($rt['banner_class'] == '0') {
                    if($rt['banner_file1']) {
                        if($rt['banner_url']) {
                            $show_file = "<a href='$rt[banner_url]' target='$rt[banner_target]'><img src='$rt[banner_file1]' width='$rt[banner_width]' height='$rt[banner_height]' border='0'></a>";
                        } else {
                            $rt['banner_url'] =  MVMMALL_SCR=='javascript' ?  MVMMALL_DIR.$rt['banner_url'] :$rt['banner_url'];
                            $show_file = "<img src='$rt[banner_file1]' width='$rt[banner_width]' height='$rt[banner_height]' border='0'>";
                        }
                    } elseif($rt['banner_link1']) {
                        if($rt['banner_url']) {
                            $show_file = "<a href='$rt[banner_url]' target='$rt[banner_target]'><img src='$rt[banner_link1]' width='$rt[banner_width]' height='$rt[banner_height]' border='0'></a>";
                        } else {
                            $rt['banner_link1'] =  MVMMALL_SCR=='javascript' ?  MVMMALL_DIR.$rt['banner_link1'] :$rt['banner_link1'];
                            $show_file = "<img src='$rt[banner_link1]' width='$rt[banner_width]' height='$rt[banner_height]' border='0'>";
                        }
                    } else {
                        $show_file = "";
                    }
                } elseif($rt['banner_class'] == '1') {
                    if($rt['banner_file1']) {
                        $show_file = "
					<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0' width='$rt[banner_width]' height='$rt[banner_height]'>
					<param name='movie' value='$rt[banner_file1]'>
					<param name='play' value='true'>
					<param name='loop' value='true'>
					<param name='quality' value='high'>
					<embed width='$rt[banner_width]' height='$rt[banner_height]' src='$rt[banner_file1]' play='true' loop='true' quality='high' pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash'>
					</embed>
					</object> 
				";
                    } elseif($rt['banner_link1']) {
                        $show_file = "
					<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0' width='$rt[banner_width]' height='$rt[banner_height]'>
					<param name='movie' value='$rt[banner_link1]'>
					<param name='play' value='true'>
					<param name='loop' value='true'>
					<param name='quality' value='high'>
					<embed width='$rt[banner_width]' height='$rt[banner_height]' src='$rt[banner_link]' play='true' loop='true' quality='high' pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash'>
					</embed>
					</object> 
				";
                    } else {
                        $show_file = "";
                    }
                }
                break;
            }else {
                $i++;
            }

        }
    }
    return $show_file ;
}

/**公告牌文章提取**/
function GetBoard($ps_name="notice",$from_record=0,$list_num=10,$cut_nums=24){
	global $rewrite,$tablepre,$db;
	$row = array();
	$mi_result = $db->query("SELECT uid,board_subject,register_date,board_hit,use_secret FROM `{$tablepre}bmain`  WHERE ps_name = '$ps_name' ORDER BY `headnum` ASC LIMIT $from_record,$list_num");
	while($list = $db->fetch_array($mi_result)) {
	    $rewrite==1 ? $list[url] = "article-$ps_name-$list[uid].html":$list[url] = "article.php?action=$ps_name&id=$list[uid]";
	    $list[use_secret]==1?$secret= " <img src=\"$GLOBALS[imgpath]/board_secret.gif\" border=\"0\">":$secret=' ';
	    $list[title]= $list[board_subject];
	    $list[subject]= cut_str($list[board_subject],$cut_nums).$secret;
	    $list[date] = date($GLOBALS['mm_date_format'],$list[register_date]);
	    unset($list[board_subject]);
	    $row[]=$list;
	}
	return $row;
}



//品牌列表
function brand_list($from_record=0,$list_num=10,$cut_nums=24){
	global $rewrite,$tablepre,$db,$imgpath;
	$brand = array();
	$result     = $db->query("SELECT id,brandname,logo,weburl,train FROM `{$tablepre}brand_table` ORDER BY `train` LIMIT $from_record,$list_num");
	while($rt = $db->fetch_array($result)) {
	    $rt['title']     = $rt['brandname'];
	    $rt['subject']   = cut_str($rt['brandname'],$cut_nums);
		$rt['url']       = $rewrite == 1 ? "brand-view-$rt[id].html" : "brand.php?action=view&id=$rt[id]" ;
		$rt['photo']     = $rt['logo']=='' ? $imgpath.'/brand.gif' : $rt['logo'];
		$brand[]         = $rt;

	}
	return $brand;
}

function GetGoods($action,$num_goods=10,$from_record=0,$use_direct=1){
	global $tablepre,$m_now_time,$db;
	$direct_where = $use_direct == 1 ? 'AND use_direct=1' :'';
	switch ($action)
    {
	case 'new':
	{
		$query =  "SELECT goods_brand,goods_rank,goods_file1,goods_sale_price,goods_point,goods_market_price,goods_hit,goods_name,uid,goods_category,goods_status,goods_class,upv,up_date,goods_rank,goods_point,goods_addoption1,goods_addoption2,goods_addoption3,goods_addoption4 FROM `{$tablepre}goods_table` WHERE goods_status = '1'  AND upv = '1' AND up_date<='$m_now_time' $direct_where ORDER BY `goods_rank` LIMIT $from_record,$num_goods";
		break;
	 }
	 case 'best':
	{
		$query =  "SELECT goods_brand,goods_file1,goods_point,goods_sale_price,goods_market_price,goods_hit,goods_name,uid,goods_category,goods_status,goods_class,upv,up_date,goods_rank,goods_point,goods_addoption1,goods_addoption2,goods_addoption3,goods_addoption4 FROM `{$tablepre}goods_table` WHERE goods_status = '2'  AND upv = '1'AND up_date<='$m_now_time' $direct_where ORDER BY `goods_rank` LIMIT $from_record,$num_goods";
		break;
	 }
	  case 'hot':
	{
		$query =  "SELECT goods_brand,goods_file1,goods_point,goods_sale_price,goods_market_price,goods_hit,goods_name,uid,goods_category,goods_status,goods_class,upv,up_date,goods_rank,goods_point,goods_addoption1,goods_addoption2,goods_addoption3,goods_addoption4 FROM `{$tablepre}goods_table` WHERE goods_status = '3' AND upv = '1' AND up_date<='$m_now_time' $direct_where ORDER BY `goods_rank` LIMIT $from_record,$num_goods";
		break;
	 }
	 
	  case 'sales':
	{
		$query =  "SELECT goods_file1,goods_point,goods_market_price,goods_sale_price,event_price,goods_name,uid,goods_category,goods_status,goods_class,upv,up_date,goods_rank,goods_code,end_date,goods_sale_stock,goods_stock FROM `{$tablepre}goods_table` WHERE goods_class = '1' AND start_date<='$m_now_time' AND end_date >= '$m_now_time'  AND upv = '1' AND up_date<='$m_now_time' ORDER BY `goods_rank`LIMIT $from_record,$num_goods";
		break;
	 }
	  default:
	  {
	      return ;
	  }
   }
   $result =  $db->query($query);
   while($list =  $db->fetch_array($result)) {
       $row[]=goods_array($list);
   }
   return $row;
}

//商品列表处理
function goods_array($list){
    global $imgpath,$mm_goods_length;
    $list['url']                =  GetBaseUrl('product',$list['uid']);
    $list['point']              =  $list['goods_point'];
    $show_addoption1            = $list['goods_addoption1'] ? "<img src=\"$imgpath/good_hot.gif\" border=\"0\">" : '';
    $show_addoption2            = $list['goods_addoption2'] ? "<img src=\"$imgpath/good_sale.gif\" border=\"0\">" : '';
    $show_addoption3            = $list['goods_addoption3'] ? "<img src=\"$imgpath/good_new.gif\" border=\"0\">" : '';
    $show_addoption4            = $list['goods_addoption4'] ? "<img src=\"$imgpath/good_none.gif\" border=\"0\">" : '';
    $list['addoption']          =  $show_addoption1. $show_addoption2. $show_addoption3. $show_addoption4;
    $list['end_date']           = date($GLOBALS['mm_date_format'],$list[end_date]);
    $list['title']              = $list['goods_name'];
    $list['subject']            = cut_str($list['goods_name'],$mm_goods_length);//商品长度限制，$mm_goods_length后台可控制
    $list['photo']              = $list['goods_file1'];
    $list['goods_market_price'] = currency($list['goods_market_price']);
    $list['rebate']             = (int)(100 - (($list['event_price'] * 100) / $list['goods_sale_price'])).'%';
    $list['goods_sale_price']   = currency($list['goods_sale_price']);
    $list['cart_url']           = "javascript:sendcart(document.getElementsByName('goods')[0],'C');";
    $list['event_price']        = currency($list['event_price']);
    unset($list['goods_name'],$list['goods_file1']);
    return $list;
}

//货币符号替换
function currency($price){
    global $mm_price_length,$mm_price_sign;
    return $mm_price_length==1 ? $mm_price_sign.sprintf("%01.2f",$price):$mm_price_sign.sprintf("%01.0f",$price);

}

//精彩全网商用短信接口函数
function sms_send($send_tel,$send_str) {
	global $mm_sms_tel,$mm_sms_system_id,$mm_sms_system_pass,$mm_sms_system_url,$m_check_id,$mm_mall_name,$mm_settimer;
	$loginname                = md5($mm_sms_system_id);//短信帐号
	$pass                     =   md5($mm_sms_system_pass);//密码
	$message                  = trim($send_str);//url编码后的短信内容
	$settimer                 = urlencode(trim($mm_settimer));//定时发送时间
	$sender_name              = urlencode("$mm_mall_name");
	$code                     = "";            //业务代码
	$subid                    = "";           //扩展号
	$sender                   = "$mm_sms_tel";//发送号码
	$allowforward             = "";         //转发支持
	$cmd                      = "send";//操作命令
	$recordid_client          = $m_check_id;  //客户短信标识
	$receivers = $send_tel;                   //接收号码
	$http = "$mm_sms_system_url";
	$file = $http."?loginname=".$loginname."&pass=".$pass."&code=".$code."&subid=".$subid."&sender=".$sender."&receivers=".$receivers."&settimer=".$settimer."&message=".urlencode($message)."&cmd=".$cmd."&allowforward=".$allowforward."&sender_name=".$sender_name."&output=&recordid_client=".$recordid_client."&charset=utf8";
	$parser = xml_parser_create(); //对像的创建
	xml_set_element_handler($parser,"startElement","endElement");
	xml_set_character_data_handler($parser, "characterData");
	$filehandler = fopen($file, "r");
	function startElement($parser_instance, $element_name, $attrs) { //对像处理函数

		switch($element_name) {
			case "SUCCESS"     :
			break;
			case "FAIL" :
			break;
			case "RETCODE":
			break;
			case "SMSREMAIN":
			break;
			case "ERRPHONES":
			break;
		}
	}
	function characterData($parser_instance, $xml_data) {
		global $value;
		$value=mb_convert_encoding($xml_data, "UTF-8", "gb2312");

	}

	function endElement($parser_instance, $element_name) {
		switch($element_name) {
			case "SUCCESS"     :
			break;
			case "FAIL" :
			break;
			case "RETCODE":
			global $RetCode;
			$RetCode=$GLOBALS['value'];

			break;
			case "SMSREMAIN":
			global $SmsRemain;
			$SmsRemain=$GLOBALS['value'];
			break;
			case "ERRPHONES":
			break;
		}
	}
	while ($data = fread($filehandler, 5000)) { //读取对像
		xml_parse($parser, $data, feof($filehandler));
	}
	if ($cmd == "send")   { sms_output_sta($GLOBALS['RetCode']); }
}

//短消息返回提示信息
function sms_output_sta($RetCode) {
	switch ($RetCode) {
		case 1: return  "发送成功"; break;
		case 0: return  "短信发送错误！";break;
		case -1: return  "用户名或密码错误！";
		break;
		case -2: return  "您对应的短信帐号已经被禁用，请与上级代理商联系！";break;
		case -3: return  "剩余短信条数不够！";	 		break;
		case -4: return  "网关错误！";break;
		case -5: return  "时间格式错误！";break;
		case -6: return  "未输入用户名或密码！";break;
		case -7: return  "未输入企业代码！";break;
		case -8: return  "url调用操作命令错误！";break;
		case -9: return  "接收号码为空！";break;
		case -10: return  "短信内容为空！";break;
		case -11: return  "发送号码为空！";break;
		case -12: return  "登录帐号停用，不能发送短信！";break;
		case -13: return  "登录帐号被禁用！";break;
		case -14: return  "接收手机号格式错误！";break;
		case -15: return  "接收离线回复短信的手机号senderPhone格式错误！";break;
		case -16: return  "源地址认证错误！";break;
		case -17: return  "无权查询回复短信！";break;
		case -18: return  "短信数据库错误！";break;
	}

}

function comma_del($str) {
	$str = eregi_replace(",", " ", $str);
	return $str;
}
function enter_del($str) {
	$str = eregi_replace("\r\n", " ", $str);
	$str = eregi_replace("\n", " ", $str);
	$str = eregi_replace("\"", " ", $str);
	return $str;
}
function template($template,$EXT="html"){
	global $mm_skin_name,$skin,$tpl_path;
	if(empty($skin)){
	    $skin = $mm_skin_name;
	}
	$path = MVMMALL_SCR=='plugins' ? "$skin/$template.$EXT":MVMMALL_ROOT."templates/$skin/$template.$EXT";
	!file_exists($path) && $path=MVMMALL_ROOT."templates/default/$template.$EXT";
	return  $path;
}

//常见伪静态url处理函数
function GetBaseUrl($name,$key='',$act='action'){
    if($GLOBALS[rewrite]==1){
        $key==''?$linkurl = "$name.html":$linkurl = "$name-$key-1.html";
    } else {
        $key==''?$linkurl = "$name.php":$linkurl  = "$name.php?$act=$key";
    }
    return $linkurl;
}

//销售排行
function sell_goods($action,$from_record,$list_num){
	global $db,$tablepre,$mm_goods_length;
     $result = $db->query("SELECT SUM(a.buy_number) as total_num,a.goods_name,a.order_id,a.goods_id,a.buy_price,a.mall_price,b.uid,b.addtime,b.status,c.uid,c.goods_stock,c.goods_cost,c.goods_file1 FROM `{$tablepre}order_goods` a INNER JOIN `{$tablepre}order_info` b ON a.order_id=b.uid INNER JOIN `{$tablepre}goods_table` c ON a.goods_id=c.uid WHERE b.status>1 AND b.status<8 GROUP BY a.goods_id  ORDER BY total_num DESC LIMIT $from_record,$list_num");
     while($rt = $db->fetch_array($result)) {
     	$co_num++;
     	$rt['total_sale'] = currency($rt['buy_price']*$rt['total_num']);
     	$rt['url']        = GetBaseUrl('product',$rt['goods_id']);
     	$rt['subject']    =  cut_str($rt['goods_name'],$mm_goods_length);
     	$rt['title']      =  $rt['subject'];
     	$rt['num']        = $co_num;
     	$rt['mall_price'] = currency($rt['mall_price']);
     	$rt['photo']      = $rt['goods_file1'];
     	$cart_rt[]        = $rt;
     }
    return $cart_rt;
}
//热门关键字搜索
function hot_search($nums=15,$type='red'){
    if(file_exists(MVMMALL_CACHE.'/hot_keywords.cache.php') && $type=='red'){
        include_once MVMMALL_CACHE.'/hot_keywords.cache.php';
        return $hot_keywords;
    }
    $hot_keywords = array();
    $start_date   = $GLOBALS['m_now_time']-(60*60*24*30);
    $result       = $GLOBALS['db']->query("SELECT COUNT(*) AS total_num, search_word FROM `{$GLOBALS['tablepre']}search_table` WHERE register_date > '$start_date' GROUP BY search_word ORDER BY total_num DESC LIMIT 0,$nums");
    while($rt     = $GLOBALS['db']->fetch_array($result)){
        $rt['title']    = $rt['search_word'];
        $rt['url']      = 'search.php?ps_search='.urlencode($rt['search_word']);
        $hot_keywords[] = $rt;
    }
    make_cache($hot_keywords,'hot_keywords');
    return $hot_keywords;
}

  function drop_menu($date,$name,$id='',$js=''){
  	$str = " <select name='$name' id='$name' $js>";
  	foreach ($date as $key=>$val){
  		$chk = $key==$id ? 'selected=selected':'';
  		$str.="<option value='$key'  $chk >$val</option>";
  	}
  	$str .= '</select>';
  	return $str;
  }
      
/**活动**/
 function activity($type=1,$from_record=0,$list_num=10){
        global $db,$tablepre,$rewrite;
        $activity_list = array();
        if ($type==1){
            $query = "SELECT a.*,b.uid,b.goods_file1,b.goods_name FROM `{$tablepre}activity` a LEFT JOIN `{$tablepre}goods_table` b ON a.goods_id=b.uid WHERE act_type='1' ORDER BY `act_id` DESC LIMIT $from_record, $list_num";
            $result = $db->query($query);
            while ($list = $db->fetch_array($result)) {
                $rewrite == 1 ? $list[url]  ="group-view-$list[act_id].html":$list[url]  = "group.php?action=view&id=$list[act_id]"; 
                $list[start_time]  = date('Y-m-d H:i', $list[start_time]);
                $list[end_time]    = date('Y-m-d H:i', $list[end_time]);
                $list[subject]     = cut_str($list[act_title],25);
                $list[title]       =  $list[act_title];
                $list[photo]       = $list[goods_file1];
                $act_config        = unserialize($list[act_config]);
                $act_config[buy_nums]>=$act_config[end_nums] && $list[end_img] = "<img src=\"$imgpath/di.jpg\">";
                $row                = array_merge($list,$act_config);
                $row[start_price]   = currency($row[start_price]);
                $row[middle_price]  = currency($row[middle_price]);
                $row[end_price]     = currency($row[end_price]);
                $row[deposit]       = currency($row[deposit]);
                $activity_list[]    = $row;
            }
            
        } elseif ($type==2){
            $query = "SELECT a.*,b.uid,b.goods_file1,b.goods_name FROM `{$tablepre}activity` a LEFT JOIN `{$tablepre}goods_table` b ON a.goods_id=b.uid WHERE act_type='2' ORDER BY `act_id` DESC LIMIT $from_record, $list_num";
            $result = $db->query($query);
            while ($list = $db->fetch_array($result)) {
                $rewrite == 1 ? $list[url]  ="auction-view-$list[act_id].html": $list[url]  = "auction.php?action=view&id=$list[act_id]";
                $list[start_time]  = date('Y-m-d', $list[start_time]);
                $list[end_time]    = date('Y-m-d', $list[end_time]);
                $list[subject]     = cut_str($list[act_title],25);
                $list[title]       =  $list[act_title];
                $list[photo]       = $list[goods_file1];
                $list[photo]       =
                $row = array_merge($list, unserialize($list[act_config]));
                $row[end_price]    = currency($row[end_price]);
                $row[start_price]  = currency($row[start_price]);
                $row[amplitude]    = currency($row[amplitude]);
                $row[deposit]      = currency($row[deposit]);
                $activity_list[]   = $row;
            }
        } elseif ($type==3){
            $query = "SELECT a.*,b.uid,b.goods_file1,b.goods_name FROM `{$tablepre}activity` a LEFT JOIN `{$tablepre}goods_table` b ON a.goods_id=b.uid WHERE act_type='3' ORDER BY `act_id` DESC";
            $result = $db->query($query);
            while ($list = $db->fetch_array($result)) {
                $list[url]         = GetBaseUrl('product',$list[uid]);
                $list[buy_url]     = "cart.php?action=privilege&act_id=$list[act_id]";
                $list[start_time]  = date('Y-m-d', $list[start_time]);
                $list[end_time]    = date('Y-m-d', $list[end_time]);
                $list[subject]     = cut_str($list[act_title],25);
                $list[title]       =  $list[act_title];
                $list[photo]       = $list[goods_file1];
                $list[photo]       =
                $row               = array_merge($list, unserialize($list[act_config]));
                $row[buy_price]    = currency($row[buy_price]);
                $order_price=floatval(str_replace($GLOBALS[mm_price_sign],'',$_SESSION[sum_cart][price]));
                $order_price>=$row[start_price]&&$order_price<=$row[end_price] && $activity_list[] = $row;
            }
        }
        return $activity_list;
    }
    
/**支付列表**/
function payment_list($type='red') {
    $payment = array();
    if($type=='red'){
        if(file_exists($GLOBALS[user_url].'data/cache/payment.cache.php')){
            require_once $GLOBALS[user_url].'data/cache/payment.cache.php';
            return $payment;
        }
    }
    $result = $GLOBALS[db]->query("SELECT id,name,pay_desc,class_name FROM `{$GLOBALS[tablepre]}payment_table`");
    while ($list = $GLOBALS[db]->fetch_array($result)){
        $payment[] = $list;
    }
    make_cache($payment,'payment');
    return $payment;
}

/**底部处理**/
function footer(){
	global $db,$mm_obstart,$imgpath,$lang,$mm_mall_address,$mm_sale_num,$mm_ceo_phone,$mm_ceo_fax,$mm_client_msn,$mm_client_qq1,$mm_company_num,$mm_client_email,$mm_mail_name,$lang_powered_mvmmall,$mvmmal_start,$nav_foot,$mmfot_logo;
	$mm_company_num && $mm_company_num = " <a href=\"http://www.miibeian.gov.cn\" target=\"_blank\">$mm_company_num</a>";
	$ft_gzip        = ($mm_obstart ==1 ? 'Gzip enabled' : 'Gzip disabled'). $mm_company_num;
	$t_arr	        = explode(' ',microtime());
	$totaltime	    = number_format(($t_arr[0]+$t_arr[1]-$mvmmal_start),6);
	if(function_exists('memory_get_usage')){
		$memory     = sprintf(',Memory occupation %0.3f MB,', memory_get_usage() / 1048576);
	}
	$mvm_spend	    = "$totaltime(s) $db->querynum queries".$memory;
	$client_email   =  mango_encode($mm_client_email);
    $mm_footer_code = stripslashes("$GLOBALS[mm_footer_code]");
	require template('footer');
	$output         = str_replace(array('<!--<!---->','<!---->-->','<!--fck-->','<!--fck','fck-->','<!---->','',"\r",substr(MVMMALL_ROOT,0,-1)),'',ob_get_contents());
	ob_end_clean();
    echo $output; unset($output);exit;
}

function  clean_html($type='show'){
    $output  = str_replace(array('<!--<!---->','<!---->-->','<!--fck-->','<!--fck','fck-->','<!---->','',"\r",substr(MVMMALL_ROOT,0,-1)),'',ob_get_contents());
    ob_end_clean();
    if ($type=='show') {
    	echo $output; unset($output);
    	exit;
    }else {
        return $output ;
    }
}

//商品属性和属性价格
function goods_att($goods_id){
 $attvalue = array();
 $attval_cart = array();
 $query = "SELECT a.*,b.id,b.att_name,b.att_type FROM `{$GLOBALS[tablepre]}att_value` a LEFT JOIN `{$GLOBALS[tablepre]}attribute` b ON a.bute_id=b.id  WHERE a.goods_id='$goods_id' ORDER BY a.att_id";
    $result = $GLOBALS[db]->query($query);
    while($list = $GLOBALS[db]->fetch_array($result)) {
        if($list[att_type]==1){
            $attval_cart[$list['bute_id']]['id']      = $list[bute_id];
            $attval_cart[$list['bute_id']]['name']    = $list[att_name];
            $attval_cart[$list['bute_id']]['value'][] = array(
                                                        'title'        => $list['att_value'],
                                                        'price'        => $list['att_price'],
                                                        'bute_id'      => $list['bute_id'],
                                                        'att_id'       => $list['att_id']
                                                          );
        }else {
           $attvalue[]=$list; 
        }
    }
    $row[0]=$attval_cart;//属性价格
    $row[1] = $attvalue;//一般属性
    return $row;
}

//支付选择列表
function pay_select($name='pay_id',$id)
{
    $payment= payment_list();
    $str="<select name=\"$name\" >";
    foreach ($payment as $val){
        $val[id]==$id ? $select_check='selected':$select_check='';
        $str.="<option value=\"$val[id]\" $select_check > $val[name] </option>";
    }
    $str.='</select>';
    return $str;
}

//购物车统计
function sun_cart(){
    require_once MVMMALL_ROOT.'./include/cart.class.php';
    $rowset  = new cart();
    $rowset->cart_list();
    unset($_SESSION['sum_cart']);
    $_SESSION['sum_cart']['price'] = currency($rowset->total_price);
    $_SESSION['sum_cart']['nums']  = $rowset->total_count;
}

//会员价格
function user_price($product){
	global $lang;
	$othe_price=array();
	$product['goods_sale_price'] = str_replace($GLOBALS['mm_price_sign'],'',$product['goods_sale_price']);
	$product['event_price']      = str_replace($GLOBALS['mm_price_sign'],'',$product['event_price']);
	if($product['goods_class']=='1'&& $product['end_date'] >$GLOBALS['m_now_time']){
		$other_price[0]['title'] = $lang['event_price'];
		$other_price[0]['price'] = currency($product['event_price']);
		$other_price[1]['title'] = $lang['event_per'];
		$other_price[1]['price'] = (int)(100 - (($product['event_price'] * 100) / $product['goods_sale_price'])) . '%';
		$other_price[2]['title'] = $lang['event_data'];
		$other_price[2]['price'] = date($GLOBALS['mm_date_format'], $product['end_date']);
	}else if($product['price_sale']=='1') {
		$query = "SELECT group_name,degree,discount,group_id FROM `{$GLOBALS['tablepre']}grade_table` WHERE show_price='1' ORDER BY degree";
		$result = $GLOBALS['db']->query($query);
		while($rt = $GLOBALS['db']->fetch_array($result)) {
			if ($GLOBALS['mm_show_price']==1){
				$rt['price']   = currency($rt['discount']*$product['goods_sale_price']/100);
				$rt['title']   = $rt['group_name'];
				$other_price[] = $rt;
			}elseif ($GLOBALS['mm_show_price']==2 && $GLOBALS['mm_group_id']==$rt['group_id']){
				$rt['price']   = currency($rt['discount']*$product['goods_sale_price']/100);
				$rt['title']   = $rt['group_name'];
				$other_price[] = $rt;
				break;
			}elseif ($GLOBALS['mm_show_price']==3 && $GLOBALS['m_check_rank']>=$rt['degree']){
				$rt['price']   = currency($rt['discount']*$product['goods_sale_price']/100);
				$rt['title']   = $rt['group_name'];
				$other_price[] = $rt;
			}
		}
	} else {
		$query = "SELECT a.*,b.group_name,b.group_id,b.degree FROM {$GLOBALS['tablepre']}enprice a LEFT JOIN {$GLOBALS['tablepre']}grade_table b ON a.group_id=b.group_id  WHERE a.goods_id='$product[uid]'";
		$result = $GLOBALS['db']->query($query);
		while($rt = $GLOBALS['db']->fetch_array($result)) {
			if ($GLOBALS['mm_show_price']==1){
				$rt['price']   = currency($rt['price']);
				$rt['title']   = $rt['group_name'];
				$other_price[] = $rt;
			}elseif ($GLOBALS['mm_show_price']==2 && $GLOBALS['mm_group_id']==$rt['group_id']){
				$rt['price']   = currency($rt['price']);
				$rt['title']   = $rt['group_name'];
				$other_price[] = $rt;
				break;
			}elseif ($GLOBALS['mm_show_price']==3 && $GLOBALS['m_check_rank']=$rt['degree']){
				$rt['price']   = currency($rt['price']);
				$rt['title']   = $rt['group_name'];
				$other_price[] = $rt;
			}
		}
	}
	unset($lang);
	return $other_price;
}


//分类下拉菜单
function cat_menu($name,$select=0,$js='')
{
    global $cache;
    unset($category);
    $category = $cache->get_cache('tree');
    $all_str  = "<select name=\"$name\" id=\"$name\"   $js><option selected value=0>----</option>";
    foreach ($category as $key=>$val)
    {
        $all_str.= " <option value=".$key.' ';
        $key==$select && $all_str.= '  selected';
        $all_str.= ">" .str_repeat( "---", $val[2]) . " " . $val[0] . "</option>\n";
    }
    $all_str .= '</select> ';
    return $all_str;
}

//获得订单商品信息
function order_goods($order_id){
    global $db,$tablepre;
    $order_id   = (int)$order_id;
    $goods      = array();
    $arr        = array();
    $result     = $db->query("SELECT a.*,b.goods_name,b.goods_sale_price,b.goods_file1,b.uid AS goods_id,b.goods_kg,b.goods_point,b.goods_code FROM `{$tablepre}order_goods` a LEFT JOIN `{$tablepre}goods_table` b ON a.goods_id=b.uid WHERE a.order_id='$order_id' ORDER BY a.uid ASC ");
    while ( $rt = $db->fetch_array($result)) {
        $goods_nums     += $rt['buy_number'];
        $money          += $rt['buy_price']   * $rt['buy_number'];
        $kg             += $rt['goods_kg']    * $rt['buy_number'];
        $point          += $rt['goods_point'] * $rt['buy_number'];
        unset($rt['goods_att']);
        foreach (unserialize($rt['att_value']) as $val){
        	$rt['goods_attr'].=$val.'<br/>';
        }
        $rt['price']     = currency($rt['buy_price']);
        $rt['point']     = $rt['goods_point'];
        $rt['kg']        = $rt['goods_kg'];
        $goods[]         = $rt;
    }
    $arr['sum']   = array('price'=>$money,'point'=>$point,'kg'=>$kg,'nums'=>$goods_nums);
    $arr['goods'] = $goods;
    return $arr;
}